<template>
    <div class="app-container">
        <el-form inline>

            <el-form-item label="用户名">
                <el-input v-model="searchTempObj.username" placeholder="用户名" />
            </el-form-item>
            <el-form-item label="手机号">
                <el-input v-model="searchTempObj.mobile" placeholder="手机号" />
            </el-form-item>
            <el-form-item label="邮箱">
                <el-input v-model="searchTempObj.email" placeholder="手机号" />
            </el-form-item>
            <el-form-item label="状态">
                <el-select v-model="searchTempObj.is_active" clearable  placeholder="请选择">
                    <el-option v-for="(item,index) in activeList" :key="index" :label="item.name" :value="item.value"></el-option>
                </el-select>
            </el-form-item>
            <!-- 查询与清空的按钮 -->
            <el-button type="primary" icon="el-icon-search" @click="search">查询</el-button>
            <el-button type="" @click="clearSearch">清空</el-button>
        </el-form>
        <div class="add-button">
            <el-button type="primary" v-if="addButtons" @click="showUser()">添加</el-button>
        </div>
        <el-table :data="usersList" v-loading="listLoading">
            <el-table-column type="index" label="序号" align="center" width="80"></el-table-column>
            <el-table-column prop="username" label="用户名" width="150" />
            <el-table-column prop="email" label="用户邮箱" />
            <el-table-column prop="is_active" label="是否启用">
                <template slot-scope="{row,$index}">
                    {{ row.is_active ? "启用":"禁用" }}
                </template>
            </el-table-column>
            <el-table-column label="权限列表">
				<template slot-scope="{row,$index}">
                    <!-- <el-tag v-for="(item,index) in row.roles" :key="item.id" type="success" style="margin: 5px;">{{item.name}}</el-tag> -->
                    <span v-for="(item,index) in row.roles" :key="item.id" style="margin: 5px;">{{item.name}}</span>
                </template>
			</el-table-column>
            <el-table-column prop="create_time" label="创建时间" width="180" />
            <el-table-column prop="update_time" label="更新时间" width="180" />
            <el-table-column label="操作" width="230" align="center">
                <template slot-scope="{row,$index}">
                    <HintButton type="primary" v-if="resetButtons" icon="el-icon-lock" size="mini" title="重置密码" @click="showResetPassword(row)">
                    </HintButton>
                    <HintButton type="primary" v-if="editButtons" icon="el-icon-edit" size="mini" title="修改用户" @click="updateUser(row)">
                    </HintButton>
                    <el-popconfirm v-if="delButtons" :title="`确定要删除${row.username}吗？`" @onConfirm="deleteUser(row)">
                        <hint-button type="danger" slot="reference" icon="el-icon-delete" size="mini"
                            title="删除用户"></hint-button>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination style="margin-top: 20px;text-align: center;" layout="prev, pager, next,jumper,->,sizes,total"
            :current-page="page" :total="total" :page-size="limit" :page-sizes="limitArr" :pager-count="pagerCount"
            @current-change="getData" @size-change="handleSizeChange">
        </el-pagination>
        <el-dialog :title="formUser.id?'修改用户':'添加用户'" :visible.sync="dialogFormVisible" :before-close="cancel">
            <el-form :model="formUser" :rules="userRules" ref="userForm" label-width="120px">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="formUser.username"></el-input>
                </el-form-item>
				<el-form-item label="手机号码" prop="mobile">
                    <el-input v-model="formUser.mobile"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="formUser.email"></el-input>
                </el-form-item>
                <el-form-item label="是否启用" prop="is_active">
                    <el-radio-group v-model="formUser.is_active">
                        <el-radio v-for="(item, index) in activeList" :key="index" :label="item['value']">{{item['name']}}</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="角色" prop="role">
                    <el-select v-model="formUser.role" multiple placeholder="请选择" style="width: 100%;">
                    <el-option v-for="item in allRolesList" :key="item.id" :label="item.name" :value="item.id">
                    </el-option>
                </el-select>
                </el-form-item>
                <el-form-item label="用户密码" v-if="!formUser.id" prop="password">
                    <el-input v-model="formUser.password" type="password" />
                </el-form-item>
                <el-form-item label="重复密码" v-if="!formUser.id" prop="repassword">
                    <el-input v-model="formUser.repassword" type="password" />
                </el-form-item>
                <el-form-item label="头像" prop="avatar">
                    <el-upload
                        class="avatar-uploader"
                        action="#"
                        accept="image/jpeg, image/gif, image/png, image/bmp, image/jpg"
                        :show-file-list="false"
                        :before-upload="beforeAvatarUpload"
                        
                    >
                        <img v-if="formUser.avatar" :src="img_domain+formUser.avatar" class="avatar" />
                        <i v-else class="el-icon-plus avatar-uploader-icon" />
                    </el-upload>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="cancel">取 消</el-button>
                <el-button type="primary" @click="addOrUpdateUser">确 定</el-button>
            </div>
        </el-dialog>
        <el-dialog title="重置密码" :visible.sync="dialogRepassword" :before-close="clearRepasswordData">
            <el-form :model="formUser" :rules="repasswordRules" ref="repasswordForm" label-width="80px">
                <el-form-item label="用户名">
                    <el-input disabled :value="formUser.username"></el-input>
                </el-form-item>
                <el-form-item label="用户密码" prop="password">
                    <el-input v-model="formUser.password" type="password" />
                </el-form-item>
                <el-form-item label="重复密码" prop="repassword">
                    <el-input v-model="formUser.repassword" type="password" />
                </el-form-item>
                
            </el-form>

            <div slot="footer">
                <el-button @click="clearRepasswordData">取 消</el-button>
                <el-button :loading="buttonLoading" type="primary" @click="saveRepassword">确 定</el-button>
                
            </div>
        </el-dialog>
    </div>
</template>

<script>

    import { mapGetters } from 'vuex'
    export default {
        name: 'User',
        data() {
            return {
                // 搜索提交
                searchObj: {
                    username: '',
                    mobile: '',
                    email: '',
                    is_active:'',
                },
                // 搜索临时存储
                searchTempObj: {
                    username: '',
                    mobile: '',
                    email: '',
                    is_active:'',
                },
                // 当前页的用户列表
                usersList: [], 
                page: 1, // 当前页码
                limit: this.$util.page.limit, // 每页记录数
                limitArr: this.$util.page.size, // 每页记录数下拉框
                pagerCount:this.$util.page.pagerCount,
                total: 0, // 总数量
                activeList:this.$util.activeList,
                // 列表加载状态
                listLoading: false,
                // 添加修改用户是否显示
                dialogFormVisible: false,
                // 设置角色是否显示
                dialogRepassword: false,
                // 当前用户信息
                formUser: {},
                // 所有角色
                allRolesList: [],

                // 添加修改用户的验证
                userRules: {
                    username: [{
                            required: true,
                            message: '请输入用户名',
                            trigger: 'blur'
                        },
                        {
                            min: 5,
                            max: 10,
                            message: '长度在 5 到 10 个字符',
                            trigger: 'blur'
                        }
                    ],
                    mobile: [{
                            required: true,
                            message: '请输入手机号',
                            trigger: 'blur'
                        },
                        {
                            pattern: /^1[3456789]\d{9}$/,
                            message: '手机号格式不正确',
                            trigger: 'blur'
                        }
                    ],
                    email: [{
                            required: true,
                            message: '请输入邮箱',
                            trigger: 'blur'
                        }, 
                        {
                            pattern: /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/,
                            message: '邮箱格式不正确',
                            trigger: 'blur'
                        }
                    ],
                    password: [{
                        required: true,
                        validator: this.validatePassword,
                        trigger: 'blur'
                    }, ],
                    repassword: [{
                        required: true,
                        validator: this.validateRePassword,
                        trigger: 'blur'
                    }, ]

                },
                repasswordRules: {
                    password: [{
                        required: true,
                        validator: this.validatePassword,
                        trigger: 'blur'
                    }, ],
                    repassword: [{
                        required: true,
                        validator: this.validateRePassword,
                        trigger: 'blur'
                    }, ]
                },
                // 按钮加载状态
                buttonLoading: true,
                
            }
        },
        computed:{
            ...mapGetters([
                'img_domain'
            ]),
            /*
                按钮的权限校验
            */
            addButtons(){
                return this.$util.isButton('system.user.add')
            },
            editButtons(){
                return this.$util.isButton('system.user.edit')
            },
            delButtons(){
                return this.$util.isButton('system.user.delete')
            },
            resetButtons(){
                return this.$util.isButton('system.user.repassword')
            }

        },
        mounted() {
            this.getData()
            this.getAllRoles()
        },
        methods: {
            async getData(pager = 1) {
                this.listLoading = true
                this.page = pager
                let {
                    page,
                    limit,
                    searchObj
                } = this
                
                let result = await this.$API.user.reqUserList({page,limit,...searchObj})
                if (result.code == 200) {
                    this.listLoading = false
                    this.usersList = result.data.items;
                    this.total = result.data.total;

                }
            },
            async getAllRoles() {
                let result = await this.$API.role.reqAllRoles()
                if (result.code == 200) {
                    this.allRolesList = result.data
                }
            },
            handleSizeChange(event) {
                this.limit = event;
                this.getData()
            },
            // 搜索
            search() {
                this.searchObj = {
                    ...this.searchTempObj
                }
                this.getData()
            },
            // 清空搜索
            clearSearch() {
                this.searchObj = this.searchTempObj = {
                    username: '',
                    mobile: '',
                    email: '',
                    is_active:'',
                }
                this.getData()
            },
            
            //密码验证规则
            validatePassword(rule, value, callback) {
                if ((typeof(this.formUser.id) == 'undefined' || !this.formUser.id) && !value) {
                    callback(new Error('请输入密码'))
                } else if (value && value.length < 6) {
                    callback(new Error('密码不能小于6'))
                } else {
                    callback()
                }
            },
            //验证重复密码规则
            validateRePassword(rule, value, callback) {
                if ((typeof(this.formUser.id) == 'undefined' || !this.formUser.id) && !value) {
                    callback(new Error('请输入重复密码'))
                } else if (this.formUser.password != this.formUser.repassword) {
                    callback(new Error('两次输入的密码不一致'))
                } else {
                    callback()
                }
            },
            clearFormUser(){
                this.formUser = {
                    is_active: true,
                    role:[],
                    avatar:''
                }
            },
            // 显示添加用户
            showUser() {
                // this.clearFormUser()
                this.dialogFormVisible = true;
                // 清空上一次的验证规则
                this.$nextTick(() => this.$refs.userForm.clearValidate())
            },
            // 更新用户
            async updateUser(row) {
                // 后台接口修改密码有问题,修改这儿不设置修改密码了
                this.dialogFormVisible = true;
                let result = await this.$API.user.reqUserInfo(row.id);
                if (result.code == 200) {
                    let data = result.data
                    if(data.roles.length > 0){
                        
                        data.role =data.roles.map(item => item.id)
                    }else{
                        data.role = []
                    }
                    this.formUser = data
                }
            },
            // 删除用户
            async deleteUser(row) {
                let result = await this.$API.user.reqDeleteUser(row.id);
                if (result.status == 204) {
                    this.$message({
                        type: 'success',
                        message: '删除成功'
                    })
                    this.getData(this.usersList.length > 1 ? this.page : this.page - 1)
                }
            },
            // 关闭添加或更新用户窗口
            cancel() {
                this.clearFormUser()
                this.dialogFormVisible = false;
                this.$nextTick(() => this.$refs.userForm.clearValidate())
            },
            // 提交添加或者修改用户
            addOrUpdateUser() {
                
                let {formUser,page} = this;
                this.$refs.userForm.validate(async (valid) => {
                    if (valid) {
                       
                        let result = await this.$API.user.reqAddOrUpdateUser(formUser)
                        if (result.code == 201 || result.code == 200) {
                            this.$message({
                                type: 'success',
                                message: formUser.id ? '修改成功' : '添加成功'
                            })
                            this.getData(formUser.id ? page : 1)
                            this.cancel()
                        }
                    } else {
                        this.$message({
                            type: "error",
                            message: formUser.id ? '修改失败' : '添加失败'
                        })
                        return false;
                    }
                });

            },
            // 显示重设密码
            showResetPassword(row) {
                this.formUser = {}
                this.formUser.pk = row.id;
                this.formUser.username = row.username
 
                this.dialogRepassword = true;
                this.buttonLoading = false;
                // 清空上一次的验证规则
                this.$nextTick(() => this.$refs.repasswordForm.clearValidate())
            },


            // 重置用户密码
            saveRepassword() {
                this.buttonLoading = true;
                this.$refs.repasswordForm.validate(async (valid) => {
                    if (valid) {
                        let {formUser} = this
                        formUser.id = formUser.pk
                        delete formUser.pk;
                        let result = await this.$API.user.reqRepassword(formUser)
                        if (result.code == 200) {
                            this.$message({
                                type: 'success',
                                message: '重置成功'
                            })
                            this.clearRepasswordData()
                            this.getData(this.page)
                        }
                        
                        this.buttonLoading = false;
                        
                    }else {
                        this.$message({
                            type: "error",
                            message: '重置失败'
                        })
                        this.buttonLoading = false;
                        return false;
                    }
                })

                
            },
            // 重置用户角色
            clearRepasswordData() {
                this.dialogRepassword = false
                this.formUser = {}

            },



            
            // 图片上传之前
            beforeAvatarUpload(file) {
                const typeList = ['image/png', 'image/jpeg', 'image/jpg', 'image/gif', 'image/bmp', 'image/webp', 'image/svg']
                
                if (!typeList.includes(file.type)) {
                    this.$message.error('上传头像图片格式不正确!');
                    return false;
                }

                const isLt2M = file.size / 1024 / 1024 < 2;

                if (!isLt2M) {
                    this.$message.error('上传头像图片大小不能超过 2MB!');
                }

                // 这里上传是为了调用已封装的接口 不然的话需要单独加验证头
                let uploadFile = new FormData();
                uploadFile.append('file', file);
                 this.$API.uploads.images(uploadFile).then(res=>{
                    if(res && res.code == 201){
                        this.formUser.avatar = res.data.file
                    }
                })
                return false;
            },
        }
    }
</script>

<style scoped>
    .search-title {
        width: 150px;
        margin: 0px 10px 0px 0px;
    }

    .add-button {
        margin: 10px 0px;
    }

    .avatar-uploader ::v-deep .el-upload {
        border-radius: 5px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }
    .avatar-uploader ::v-deep .el-upload:hover {
        border-color: #409eff;
    }
    .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 100px;
        height: 100px;
        line-height: 100px;
        text-align: center;
    }
    .avatar {
        width: 100px;
        height: 100px;
        display: block;
    }

</style>
